package server.whiteboard;

import com.alibaba.fastjson.JSON;
import dao.UserDAO;

import java.io.IOException;
import java.net.*;

public class WhiteBoardRequestThread extends Thread{

    private DatagramSocket datagramSocket;
    private DatagramPacket datagramPacket;

    public WhiteBoardRequestThread(DatagramSocket datagramSocket, DatagramPacket datagramPacket) {
        this.datagramSocket = datagramSocket;
        this.datagramPacket = datagramPacket;
    }

    @Override
    public void run() {
        try {
            byte[] arr = datagramPacket.getData(); // 获取数据
            int len = datagramPacket.getLength(); // 获取有效长度
            WbRequest wbRequest = JSON.toJavaObject(JSON.parseObject(new String(arr, 0, len)), WbRequest.class);
            if (!isValid(wbRequest)) {
                return;
            }
            String str = datagramPacket.getAddress().toString();
            wbRequest.setAddress(str.substring(1, str.length()) + ":" + datagramPacket.getPort());
            RequestContext rct = RequestContext.begin(wbRequest, datagramSocket);
            WbRequestHandler.handle(rct);
            rct.end();
        } catch (Exception ignored) {
        }
//        System.out.println(new String(arr, 0, len));
    }

    /**
     * 验证请求是否合法
     */
    private boolean isValid(WbRequest wbRequest) {
        long user_id = wbRequest.getUser_id();
        String token = wbRequest.getToken();
        String userToken = UserDAO.ME.readUserToken(user_id);
        return userToken != null && userToken.equals(token);
    }

    /**
     * 请求上下文信息
     */
    public final static class RequestContext {
        WbRequest request;
        DatagramSocket datagramSocket;

        static RequestContext begin(WbRequest request, DatagramSocket datagramSocket) {
            RequestContext rct = new RequestContext();
            rct.request= request;
            rct.datagramSocket = datagramSocket;
            return rct;
        }

        public String param(String name) {
            return request.getParams_map().getOrDefault(name, "");
        }

        public String getRequestURL() {
            return request.getRequest_url();
        }

        public String getAddress() {
            return request.getAddress();
        }

        public void sendResponse(WbResponse wbResponse, String targetAddress) {
            String[] hostAndPort = targetAddress.split(":");
            send(wbResponse.json().getBytes(), hostAndPort[0], Integer.valueOf(hostAndPort[1]));
        }

        public void send(byte[] msg, String host, int port) {
            try {
                DatagramPacket datagramPacket = new DatagramPacket(msg, msg.length, InetAddress.getByName(host), port);
                datagramSocket.send(datagramPacket);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        void end() {

        }
    }
}
